package com.uy.cuantoconocesdeuruguay;

import java.util.LinkedList;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.uy.cuantoconocesdeuruguay.animations.HeightResizeAnimation;
import com.uy.cuantoconocesdeuruguay.animations.WidthResizeAnimation;
import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.datatypes.RandomImageEnvelope;
import com.uy.cuantoconocesdeuruguay.dialogs.EnlargeImageDialogUtils;
import com.uy.cuantoconocesdeuruguay.server.ImagesFetcher;
import com.uy.cuantoconocesdeuruguay.server.ServerInfo;
import com.uy.cuantoconocesdeuruguay.utiles.MetricsUtiles;
import com.uy.cuantoconocesdeuruguay.utiles.SoundsUtils;
import com.uy.cuantoconocesdeuruguay.utiles.StringPool;
import com.uy.cuantoconocesdeuruguay.utiles.SystemConstants;
import com.uy.cuantoconocesdeuruguay.view.AutoResizeTextView;

@SuppressLint("NewApi")
public abstract class ImageBaseActivity extends BaseActivity{	
	
	protected void initBoard(){
		removableBoxes.clear();
		resizeActionButtons();
		dp1 = (int) MetricsUtiles.convertDpToPixel(1, getApplicationContext());
		dp90 = (int) MetricsUtiles.convertDpToPixel(90, getApplicationContext());
		LinearLayout imageInfoContainer = (LinearLayout)findViewById(R.id.imageInfoContainer);
		LayoutParams params = imageInfoContainer.getLayoutParams();
		params.height = dp1;
		imageInfoContainer.setLayoutParams(params);
		if (android.os.Build.VERSION.SDK_INT > 10) {
			imageInfoContainer.setAlpha(0);
		}

		fieldsLettersWidth = getMaxWordLength(word); 
		int fieldPadding = (int) MetricsUtiles.convertDpToPixel(1, getApplicationContext());
		float ratioX = getResources().getDisplayMetrics().widthPixels / 480.0f;		
		int fieldSize = 480 / fieldsLettersWidth;	
		int boxSize = 480 / boxesLettersWidth;
		
		boxesHolderSize = (int) (boxSize*ratioX);
		fieldsHolderSize = (int) (fieldSize*ratioX);

		fieldsHolderFontSize = (int) (fieldsHolderSize*0.7f);
		boxesHolderFontSize = (int) (boxesHolderSize*0.7f);

		LayoutParams fieldHolderLayoutParams = new LayoutParams(fieldsHolderSize, fieldsHolderSize);

		LinearLayout fila1 = (LinearLayout)findViewById(R.id.fila1);
		fila1.removeAllViews();
		LinearLayout fila2 = (LinearLayout)findViewById(R.id.fila2);
		fila2.removeAllViews();
		LinearLayout fila3 = (LinearLayout)findViewById(R.id.fila3);
		fila3.removeAllViews();
		LinearLayout box1 = (LinearLayout)findViewById(R.id.boxes1);
		box1.removeAllViews();
		LinearLayout box2 = (LinearLayout)findViewById(R.id.boxes2);
		box2.removeAllViews();
		LinearLayout box3 = (LinearLayout)findViewById(R.id.boxes3);
		box3.removeAllViews();
		LinearLayout box4 = (LinearLayout)findViewById(R.id.boxes4);
		box4.removeAllViews();
		timerTextView = (TextView)findViewById(R.id.timerTextView);
		puntajeTextView = (TextView)findViewById(R.id.puntajeTextView);
		
		trimmedWord = word.replace(StringPool.SPACE, StringPool.BLANK);
		shuffledWord = trimmedWord;//shuffleBoxes(trimmedWord);
		fields_ids = new int[shuffledWord.length()];
		if (shuffledWord.length() < boxesLettersWidth){
			randomLettersQuantity = boxesLettersWidth;
		}else if (shuffledWord.length() < boxesLettersWidth*2){
			randomLettersQuantity = boxesLettersWidth*2;
		}else if (shuffledWord.length() < boxesLettersWidth*3){
			randomLettersQuantity = boxesLettersWidth*3;
		}else{
			randomLettersQuantity = boxesLettersWidth*4;
		}
		boxes_ids = new int[randomLettersQuantity];
		int h = 0;
		LinearLayout fila = fila1;
		LinearLayout boxes = box1;
		boolean has2Articles = has2Articles(word);
		boolean firstArticlePassed = false; 
		char SPACE_CHAR = ' ';
		for ( char c : word.toCharArray()){
			if (c != SPACE_CHAR){
				LinearLayout fieldHolder = new LinearLayout(getApplicationContext());
				fieldHolder.setLayoutParams(fieldHolderLayoutParams);
				final AutoResizeTextView letterField = new AutoResizeTextView(getApplicationContext());
				fieldHolder.setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						onFieldClickListenerImpl(letterField);
					}
				});
				letterField.setLayoutParams(new FrameLayout.LayoutParams(fieldsHolderFontSize, fieldsHolderFontSize));
				letterField.setId(letter_fields[h]);
				letterField.setTextColor(ALPHA_BLACK);
				letterField.setTextSize(500);
				letterField.setPadding(fieldPadding, fieldPadding, fieldPadding, fieldPadding);
				letterField.setTypeface(Typeface.create(StringPool.CALIBRI, Typeface.NORMAL));
				letterField.setText(StringPool.BLANK);
				letterField.setGravity(Gravity.CENTER);
				fieldHolder.addView(letterField);
				fieldHolder.setGravity(Gravity.CENTER);
				fieldHolder.setBackgroundResource(R.drawable.placeholder);
				if (android.os.Build.VERSION.SDK_INT > 10) {
					fieldHolder.setAlpha(0.87f);
				}
				fila.addView(fieldHolder);
				fields_ids[h] = letter_fields[h];
				
				//ADD BOX
				if (h < boxesLettersWidth){
					boxes = box1;
				}else if (h < boxesLettersWidth*2){
					boxes = box2;
				}else if (h < boxesLettersWidth*3){
					boxes = box3;
				}else{
					boxes = box4;
				}
				addBox(boxes, String.valueOf(c), h,true);
				
				++h;
			}else{
				if (fila == fila1){
					fila = fila2;
				}else if (fila == fila2){
					if (has2Articles && !firstArticlePassed){
						firstArticlePassed = true;
						//ADD DUMMY BLANK CONTAINER AS A SPACE 
						LinearLayout fieldHolder = new LinearLayout(getApplicationContext());
						fieldHolder.setLayoutParams(fieldHolderLayoutParams);
						fila.addView(fieldHolder);
					}else{
						fila = fila3;
					}
				}
			}
		}

		Random rand = new Random(SystemConstants.getTime());
		for (int j=shuffledWord.length() ; j<randomLettersQuantity ; ++j){
			if (j < letter_fields.length){
				TextView letterField = (TextView)findViewById(letter_fields[j]);
				if (letterField != null){
					letterField.setText(StringPool.BLANK);
				} 
			}
			String letter = String.valueOf(randomChars.charAt(rand.nextInt(randomChars.length())));
			if (j < boxesLettersWidth){
				boxes = box1;
			}else if (j < boxesLettersWidth*2){
				boxes = box2;
			}else if (j < boxesLettersWidth*3){
				boxes = box3;
			}else{
				boxes = box4;
			}
			addBox(boxes, letter, j,false);
		}
	}
	
	private synchronized void onFieldClickListenerImpl(final AutoResizeTextView letterField){
		if (!letterField.getText().toString().equals(StringPool.BLANK)){
			SoundsUtils.playSound(getApplicationContext(), R.raw.click_up);
			clickOnLetterField(letterField);
		}
	}
	
	protected void postCreate() throws Exception{
		TextView imageInfoText = (TextView)findViewById(R.id.imageInfoText);
		imageInfoText.setText(envelope.getImageInfo());
		ImageView imageInfoIcon = (ImageView)findViewById(R.id.imageInfoIcon);
		if (envelope.getImageInfo().equals(StringPool.BLANK)){
			imageInfoIcon.setVisibility(View.GONE);
		}
		threadRunning = true;		
		word = envelope.getWord(); 
		initBoard();		
			
		shuffleBoxes();
		startTimer();		
		
        imageFetcherAsyncTask = new AsyncTask<Void, Void, Void>() {
        	private ImagesFetcher imagesFetcher;
			@Override
        	protected Void doInBackground(Void... arg0) {
//				System.err.println("Started fetching image");
        		if (thumbnail == null){
        			imagesFetcher = new ImagesFetcher();
        			Drawable drawable = imagesFetcher.fetchImage(ImageBaseActivity.this, envelope.getThumbnailURL(), true);
        			thumbnail = drawable;
        		}
        		return null; 
        	}
        	@Override
        	protected void onPostExecute(Void result) {
        		final ImageView pictureImageView = (ImageView)findViewById(R.id.pictureImageView);
        		pictureImageView.setImageDrawable(thumbnail);
        		ProgressBar loader = (ProgressBar)findViewById(R.id.mainImageLoader);
        		loader.setVisibility(View.INVISIBLE);
        		pictureImageView.setOnClickListener(new OnClickListener() {							
					@Override
					public void onClick(View v) {
		        		EnlargeImageDialogUtils utils = new EnlargeImageDialogUtils(ImageBaseActivity.this);
		        		utils.setEnvelope(envelope);
		        		utils.createEnlargeImagePopup(thumbnail, (ImageBaseActivity.this instanceof FriendChallengeImage) );
		        		utils.setImagePlaceholder(pictureImageView);
					}
				});
//				System.err.println("Finished fetching image");
        	}
        	@Override
        	protected void onCancelled() {
        		if (imagesFetcher != null){
        			imagesFetcher.onCancel();
        		}
        	}
        };
		if (android.os.Build.VERSION.SDK_INT > 10) {
			imageFetcherAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			imageFetcherAsyncTask.execute();
		}
        finishedLoading = true;
        
        setupAutoFill_DEBUG();
	} 

	private void resizeActionButtons() {
		float ratio = getResources().getDisplayMetrics().widthPixels / 480.0f;		
		int layoutSize = (int) ((480 / 8)*ratio);	
		LinearLayout layoutToResize = (LinearLayout)findViewById(R.id.undoLayout);
		layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
		
		layoutToResize = (LinearLayout)findViewById(R.id.deleteLayout);
		layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
		
		layoutToResize = (LinearLayout)findViewById(R.id.hintLayout);
		if (layoutToResize != null){
			layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
		}
		
		layoutToResize = (LinearLayout)findViewById(R.id.bombLayout);
		if (layoutToResize != null){
			layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
		}
		
		layoutToResize = (LinearLayout)findViewById(R.id.helpLayout);
		layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
		
		layoutToResize = (LinearLayout)findViewById(R.id.shuffle);
		layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
		
		layoutToResize = (LinearLayout)findViewById(R.id.skipLayout);
		layoutToResize.setLayoutParams(new LinearLayout.LayoutParams(layoutSize, layoutSize));
	}

	private boolean has2Articles(String word) {
		String[] tokens = word.split(StringPool.SPACE);
		return tokens.length==4;
	}
	private int getMaxWordLength(String word) {
		int maxLength = boxesLettersWidth;
		String[] words = word.split(StringPool.SPACE);
		for (String w : words){
			maxLength = Math.max(maxLength, w.length());//w.length() > maxLength ? w.length() : maxLength;
		}
		if (has2Articles(word)){
			maxLength = Math.max(maxLength, words[1].length() + words[2].length() + 1);
		}
		return maxLength;
	}
	protected void shuffleBoxes() {
		Random rand = new Random(SystemConstants.getTime());
		int max = rand.nextInt(trimmedWord.length()) + 10;
		for (int i=0 ; i<max ; ++i){
			int j = rand.nextInt(randomLettersQuantity);
			int k = rand.nextInt(randomLettersQuantity);
			TextView box1 = (TextView)findViewById(letter_boxes[j]);
			TextView box2 = (TextView)findViewById(letter_boxes[k]);
			String pivot = box1.getText().toString();
			box1.setText(box2.getText());
			box2.setText(pivot); 
			if (removableBoxes.contains(box1)){
				if (!removableBoxes.contains(box2)){
					removableBoxes.remove(box1);
					removableBoxes.add(box2);
				}
			}else if (removableBoxes.contains(box2)){
				if (!removableBoxes.contains(box1)){
					removableBoxes.remove(box2);
					removableBoxes.add(box1);
				}
			}
		}
	}
	
	private void addBox(LinearLayout boxes, final String letter, int i, boolean originalWord) {
		LinearLayout boxHolder = new LinearLayout(getApplicationContext());
		boxHolder.setLayoutParams(new LayoutParams(boxesHolderSize, boxesHolderSize));
		final AutoResizeTextView letterBox = new AutoResizeTextView(getApplicationContext());
		boxHolder.setOnClickListener(new OnClickListener() {					
			@Override
			public void onClick(View v) {
				onBoxClickListenerImpl(letterBox);
			}
		});
		letterBox.setLayoutParams(new FrameLayout.LayoutParams(boxesHolderFontSize, boxesHolderFontSize));
		letterBox.setTextColor(ALPHA_BLACK);
		letterBox.setTextSize(500);
		letterBox.setText(letter);
		letterBox.setTypeface(Typeface.create(StringPool.CALIBRI, Typeface.NORMAL));
		letterBox.setGravity(Gravity.CENTER);
		letterBox.setId(letter_boxes[i]);
		boxes_ids[i] = letter_boxes[i];
		boxHolder.addView(letterBox);
		boxHolder.setGravity(Gravity.CENTER);
		boxHolder.setBackgroundResource(R.drawable.placeholder);
		boxes.addView(boxHolder);
		if (!originalWord){
			removableBoxes.add(letterBox);
		}
	} 
	
	private synchronized void onBoxClickListenerImpl(final AutoResizeTextView letterBox){
		if (!letterBox.getText().toString().equals(StringPool.BLANK)){
			int usedLetters = getUsedLetters();
			if (usedLetters == shuffledWord.length()){
				return;
			}
			SoundsUtils.playSound(getApplicationContext(), R.raw.click_down);
			clickOnBox(letterBox,true);
			letterBox.setText(StringPool.BLANK);
		}
	}

	private int getUsedLetters() {
		int usedLetters = 0;
		for (int id : fields_ids){ 
			TextView letterField = (TextView)findViewById(id);
			if (!letterField.getText().toString().equals(StringPool.BLANK)){
				++usedLetters;
			}
		}
		return usedLetters;
	}

	private void clickOnBox(TextView letterBox_param, boolean add) {
		String letter = letterBox_param.getText().toString();
		if (add){
			for (int id : fields_ids){
				TextView letterField = (TextView)findViewById(id);
				if (letterField.getText().toString().equals(StringPool.BLANK)){
					LinearLayout fieldHolder = (LinearLayout)letterField.getParent();
					animateShowingField(letterField);
					lettersHistory.add(fieldHolder);
					letterField.setText(letter);
					
					//Adjust removable boxes
					if (removableBoxes.contains(letterBox_param)){
						removableBoxes.remove(letterBox_param);
						removableBoxes.add(letterField);
					}
					return;
				}
			}
		}else{
			for (int id : boxes_ids){
				TextView letterBox = (TextView)findViewById(id);
				lettersHistory.remove(letterBox.getParent());
				if (letterBox.getText().toString().equals(StringPool.BLANK)){
					animateShowingBox(letterBox);
					animateHidingField(letterBox_param);
					letterBox.setText(letter);
					soundPlayed = false;

					//Adjust removable boxes
					if (removableBoxes.contains(letterBox_param)){
						removableBoxes.remove(letterBox_param);
						removableBoxes.add(letterBox);
					}
					return; 
				}
			}
		}
	}
	
	//ANIMATING FIELDS
	protected void animateShowingField(final TextView letterField) {
		WidthResizeAnimation widthAnimation = new WidthResizeAnimation(letterField);
		widthAnimation.setDuration(200);
		widthAnimation.setParams(1, fieldsHolderFontSize);
		HeightResizeAnimation heightResizeAnimation = new HeightResizeAnimation(letterField, false);
		heightResizeAnimation.setDuration(200);
		heightResizeAnimation.setParams(1, fieldsHolderFontSize);
		letterField.startAnimation(widthAnimation);
		letterField.startAnimation(heightResizeAnimation);
		
		heightResizeAnimation.setAnimationListener(new AnimationListener() {			
			@Override
			public void onAnimationStart(Animation arg0) {}			
			@Override
			public void onAnimationRepeat(Animation arg0) {}			
			@Override
			public void onAnimationEnd(Animation arg0) {
				checkWord();
			}
		});
	}	
	private void animateHidingField(final TextView letterField) {
		WidthResizeAnimation widthAnimation = new WidthResizeAnimation(letterField);
		widthAnimation.setDuration(200);
		widthAnimation.setParams(fieldsHolderFontSize, 1);
		HeightResizeAnimation heightResizeAnimation = new HeightResizeAnimation(letterField, false);
		heightResizeAnimation.setDuration(200);
		heightResizeAnimation.setParams(fieldsHolderFontSize, 1);
		letterField.startAnimation(widthAnimation);
		letterField.startAnimation(heightResizeAnimation);
	}
	
	//ANIMATING BOXES
	private void animateShowingBox(final TextView letterBox) {
		WidthResizeAnimation widthAnimation = new WidthResizeAnimation(letterBox);
		widthAnimation.setDuration(200);
		widthAnimation.setParams(1, boxesHolderFontSize);
		HeightResizeAnimation heightResizeAnimation = new HeightResizeAnimation(letterBox, false);
		heightResizeAnimation.setDuration(200);
		heightResizeAnimation.setParams(1, boxesHolderFontSize);
		letterBox.startAnimation(widthAnimation);
		letterBox.startAnimation(heightResizeAnimation);
	}
	
	protected void animateHidingBox(final TextView letterBox) {
		WidthResizeAnimation widthAnimation = new WidthResizeAnimation(letterBox);
		widthAnimation.setDuration(200);
		widthAnimation.setParams(boxesHolderFontSize, 1);
		HeightResizeAnimation heightResizeAnimation = new HeightResizeAnimation(letterBox, false);
		heightResizeAnimation.setDuration(200);
		heightResizeAnimation.setParams(boxesHolderFontSize, 1);
		letterBox.startAnimation(widthAnimation);
		letterBox.startAnimation(heightResizeAnimation);
	}
	public void undo(View view){
		if (lettersHistory.isEmpty()){
			return;
		}
		LinearLayout lastLayout = lettersHistory.removeLast();
		TextView letterField = (TextView) lastLayout.getChildAt(0);
		clickOnLetterField(letterField);
	}

	public void delete(View view){
		if (lettersHistory.isEmpty()){
			return;
		}
		while (!lettersHistory.isEmpty()){
			undo(view);
		}
	}

	private void clickOnLetterField(TextView letterField) {		
		if (!letterField.getText().toString().equals(StringPool.BLANK)){
//			--getUsedLetters();
			clickOnBox(letterField,false);
			letterField.setText(StringPool.BLANK);
		}			
	}
	public void help(View view){ 
		Session session = Session.getActiveSession();
		if (session == null || !session.isOpened()){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.image_base_activity_must_login_with_facebook));
			builder.setPositiveButton(getString(R.string.accept), null);
		    builder.setCancelable(true);
		    AlertDialog dialog = builder.create();
		    dialog.show();
			return;
		}else{
			session.refreshPermissions();
			if (!session.isPermissionGranted("publish_actions")){
				session.requestNewPublishPermissions(new Session.NewPermissionsRequest(ImageBaseActivity.this, MainActivity.WRITE_PERMISSIONS));
				return;
			}
		} 
		showPostConfirmMessage();
	}
	private void showPostConfirmMessage() {
		final Session session = Session.getActiveSession();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.image_base_activity_publish_on_facebook_confirm));
	    builder.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
	    	@Override
	    	public void onClick(DialogInterface dialog, int id) {
	        	String imageInfoString = 
	        			envelope.getRelativeImageURL()+StringPool.COMMA+
	        			MainActivity.userData.getFacebookName()+StringPool.COMMA+
	        			envelope.getImageInfo();
	        	String data = "imageInfo="+Base64.encodeToString(imageInfoString.getBytes(), Base64.DEFAULT);
	        	Bundle params = new Bundle();
	        	JSONObject jsonObject = new JSONObject();
	        	try {
					jsonObject.put("value", "SELF");
				} catch (JSONException e) {
					GoogleAnalyticsTracker.trackException(ImageBaseActivity.this, e);
					e.printStackTrace();  
				}
	        	params.putString("privacy", jsonObject.toString());
	        	params.putString("message", getString(R.string.image_base_activity_publish_on_facebook_message));
	        	params.putString("name", "Trivia Uruguay");
	        	params.putString("link", ServerInfo.SERVER_HOST+"web/viewImage.php?"+data);
	        	params.putString("description", getString(R.string.image_base_activity_publish_on_facebook_description));
	        	params.putString("picture", envelope.getImageURL());
	            Request postToWall = Request.newStatusUpdateRequest(session, getString(R.string.image_base_activity_publish_on_facebook_title), new Request.Callback() {
    	            @Override
    	            public void onCompleted(Response response){    	  
    	            }
                });
	            postToWall.setParameters(params);
	            Request.executeBatchAsync(postToWall);
	            Toast.makeText(ImageBaseActivity.this, getString(R.string.image_base_activity_publish_on_facebook_sent), Toast.LENGTH_SHORT).show();
	    	} 
	    });
	    
	    builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int id) {
	    		Toast.makeText(ImageBaseActivity.this, getString(R.string.image_base_activity_publish_on_facebook_cancel), Toast.LENGTH_SHORT).show();
	    	} 
	    }); 
	    builder.setCancelable(true);
	    AlertDialog dialog = builder.create();
	    dialog.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    Session session = Session.getActiveSession();
	    session.onActivityResult(this, requestCode, resultCode, data);
	    session.refreshPermissions();
		if (session.isPermissionGranted("publish_actions")){
			showPostConfirmMessage();
		}
	}
	public void toggleImageInfo(View view){
		if (!envelope.getImageInfo().equals(StringPool.BLANK)){
			LinearLayout imageInfoContainer = (LinearLayout)findViewById(R.id.imageInfoContainer);
			if (imageInfoContainer.getLayoutParams().height == dp1){
				HeightResizeAnimation showAnimation = new HeightResizeAnimation(imageInfoContainer,false);
		    	showAnimation.setParams(dp1, dp90);
		    	imageInfoContainer.startAnimation(showAnimation);		
			}else{
				HeightResizeAnimation showAnimation = new HeightResizeAnimation(imageInfoContainer,false);
		    	showAnimation.setParams(dp90, dp1);
		    	imageInfoContainer.startAnimation(showAnimation);
	    	}
		}
	}
	public void shuffle(View view){
		shuffleBoxes();
	}
	
	public abstract void nextQuestion(View view);
	protected abstract void checkWord();
	
	private void startTimer(){
		threadRunning = true;
		pictureScore = MAX_TIME / (60000);
		AsyncTask<Void, Void, Void> timerThread = new AsyncTask<Void, Void, Void>(){
			private int timeRemaining, minutes, seconds;
			private String minutesString, secondsString;
			@Override
			protected Void doInBackground(Void... params) {
//				System.err.println("Started timer thread...");
				long lastSystemTime = SystemClock.elapsedRealtime();//System.currentTimeMillis();
				while ((timeElapsed < MAX_TIME) && threadRunning){					
					timeElapsed += SystemClock.elapsedRealtime() - lastSystemTime;
					lastSystemTime = SystemClock.elapsedRealtime();//System.currentTimeMillis();
					timeRemaining = MAX_TIME - timeElapsed;
					seconds = timeRemaining/1000;
					minutes = seconds/60;
					seconds = seconds % 60;
					minutesString = minutes < 10 ? StringPool.ZERO+minutes : String.valueOf(minutes);
					secondsString = seconds < 10 ? StringPool.ZERO+seconds : String.valueOf(seconds);
					pictureScore = minutes+1;//LA IMAGEN DA LA MISMA CANTIDAD DE PUNTOS QUE DE MINUTOS RESTANTES
					runOnUiThread(new Runnable() {
						public void run() {
							timerTextView.setText(minutesString+StringPool.S_COLON_S+secondsString);
							puntajeTextView.setText( String.valueOf(pictureScore));
						}
					});
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
//						GoogleAnalyticsTracker.trackException(ImageBaseActivity.this, e);
						e.printStackTrace();
					}
//					System.err.println("Running timer thread...");
				}

//				System.err.println("Stopping timer thread...");
				if (threadRunning){
					runOnUiThread(new Runnable() {
						public void run() {
							timeUp = true;
							Toast.makeText(ImageBaseActivity.this, getString(R.string.image_base_activity_time_up), Toast.LENGTH_SHORT).show();
							if (onForeground){
								SoundsUtils.playSound(getApplicationContext(), R.raw.incorrect_answer);
								nextQuestion(null);
							}
						}
					});
				}
				return null;
			}
		};

		if (android.os.Build.VERSION.SDK_INT > 10) { 
			timerThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			timerThread.execute();
		}
	}

	protected void stopTimer(){
		if (imageFetcherAsyncTask != null){
			imageFetcherAsyncTask.cancel(true);
		}
		threadRunning = false;
	}
	@Override
	protected void onResume() {
		onForeground = true;
		super.onResume();
	}
	@Override
	protected void onPause() {
		onForeground = false;
		super.onPause();
	}
	
	private int boxesHolderSize, fieldsHolderSize;
	private int randomLettersQuantity;
	private int fieldsLettersWidth;		
	private int fieldsHolderFontSize;
	private int boxesHolderFontSize;
	private boolean threadRunning;
	private TextView timerTextView,puntajeTextView;
	private String shuffledWord;
	private int dp90;
	private int dp1;
	private AsyncTask<Void, Void, Void> imageFetcherAsyncTask;
	private static Drawable thumbnail;
	private static final String randomChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static final int boxesLettersWidth = 8;
	private static final int[] letter_boxes = {R.id.letter_box1,R.id.letter_box2,R.id.letter_box3,R.id.letter_box4,R.id.letter_box5,R.id.letter_box6,R.id.letter_box7,R.id.letter_box8,R.id.letter_box9,R.id.letter_box10,R.id.letter_box11,R.id.letter_box12,R.id.letter_box13,R.id.letter_box14,R.id.letter_box15,R.id.letter_box16,R.id.letter_box17,R.id.letter_box18,R.id.letter_box19,R.id.letter_box20,R.id.letter_box21,R.id.letter_box22,R.id.letter_box23,R.id.letter_box24,R.id.letter_box25,R.id.letter_box26,R.id.letter_box27,R.id.letter_box28,R.id.letter_box29,R.id.letter_box30,R.id.letter_box31,R.id.letter_box32,R.id.letter_box33,R.id.letter_box34,R.id.letter_box35,R.id.letter_box36,R.id.letter_box37,R.id.letter_box38,R.id.letter_box39,R.id.letter_box40,R.id.letter_box41,R.id.letter_box42,R.id.letter_box43,R.id.letter_box44,R.id.letter_box45,R.id.letter_box46,R.id.letter_box47,R.id.letter_box48};
	private static final int[] letter_fields = {R.id.letter_field1,R.id.letter_field2,R.id.letter_field3,R.id.letter_field4,R.id.letter_field5,R.id.letter_field6,R.id.letter_field7,R.id.letter_field8,R.id.letter_field9,R.id.letter_field10,R.id.letter_field11,R.id.letter_field12,R.id.letter_field13,R.id.letter_field14,R.id.letter_field15,R.id.letter_field16,R.id.letter_field17,R.id.letter_field18,R.id.letter_field19,R.id.letter_field20,R.id.letter_field21,R.id.letter_field22,R.id.letter_field23,R.id.letter_field24,R.id.letter_field25,R.id.letter_field26,R.id.letter_field27,R.id.letter_field28,R.id.letter_field29,R.id.letter_field30,R.id.letter_field31,R.id.letter_field32,R.id.letter_field33,R.id.letter_field34,R.id.letter_field35,R.id.letter_field36,R.id.letter_field37,R.id.letter_field38,R.id.letter_field39,R.id.letter_field40,R.id.letter_field41,R.id.letter_field42,R.id.letter_field43,R.id.letter_field44,R.id.letter_field45,R.id.letter_field46,R.id.letter_field47,R.id.letter_field48};
	private static final int ALPHA_BLACK = Color.argb(221, 0, 0, 0);
    
	protected String word;
	protected String trimmedWord;
	protected boolean timeUp = false,finishedLoading;
	protected boolean soundPlayed;
	protected boolean onForeground;
	protected int timeElapsed = 0;
	protected int pictureScore;
	protected long lastNextQuestionClickTime;
	protected int[] fields_ids;
	protected int[] boxes_ids;
	protected Dialog loaderDialog;
	protected static RandomImageEnvelope envelope;
	protected static final LinkedList<TextView> removableBoxes = new LinkedList<TextView>();
	protected static final LinkedList<LinearLayout> lettersHistory = new LinkedList<LinearLayout>();
	
	public static int MAX_TIME;
	public static void reset(){
		envelope = null;
		thumbnail = null;
	}
	
	

	private void setupAutoFill_DEBUG() {
		LinearLayout skipLayout = (LinearLayout)findViewById(R.id.skipLayout);
        skipLayout.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				for (int i=0 ; i<trimmedWord.length() ; ++i){
					String letter = trimmedWord.substring(i, i+1);
					TextView letterField = (TextView)findViewById(letter_fields[i]);
					animateShowingBox(letterField);
					letterField.setText(letter);
				}
				soundPlayed = false;
				AsyncTask<Void, Void, Void> delayedCheck = new AsyncTask<Void, Void, Void>(){
					@Override
					protected Void doInBackground(Void... params) {
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						return null;
					}
					@Override
					protected void onPostExecute(Void result) {
						checkWord();
					}
				};

				if (android.os.Build.VERSION.SDK_INT > 10) { 
					delayedCheck.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
				}else{
					delayedCheck.execute();
				}
				return true;
			}
		});
	}
}
